package com.syncshot.androidapp.adapters;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;

public class EfficientListAdapter<TBOItem> extends ArrayAdapter<TBOItem> {

    private static final String                            TAG                 = "EfficientListAdapter";

    protected int                                          mElementResLayoutId;
    protected Class<? extends AbstractViewHolder<TBOItem>> mViewHolderClass;

    public EfficientListAdapter(Context context, int elementResLayoutId, Class<? extends AbstractViewHolder<TBOItem>> viewHolderClass, List<TBOItem> list) {
        super(context, 0, 0, list);
        mElementResLayoutId = elementResLayoutId;
        mViewHolderClass = viewHolderClass;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View view = computeView(position, convertView, parent, mElementResLayoutId, mViewHolderClass);

        return view;
    }

    /**
     * Efficiently compute a view from a convertView, a res id, and a view holder class (Pattern view holder)
     */
    protected View computeView(int position, View convertView, ViewGroup parent, int resId, Class<? extends AbstractViewHolder<TBOItem>> viewHolderClass) {
        return computeView(position, convertView, parent, resId, viewHolderClass, (TBOItem) getItem(position));
    }

    /**
     * Efficiently compute a view from a convertView, a res id, and a view holder class (Pattern view holder)
     */
    protected View computeView(int position, View convertView, ViewGroup parent, int resId, Class<? extends AbstractViewHolder<TBOItem>> viewHolderClass, TBOItem item) {
        // Try to use convert view
        View view = null;
        if (convertView != null) {
            view = convertView;
        }

        AbstractViewHolder<TBOItem> viewHolder = null;
        if (view == null) {
            view = ((LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(resId, null, false);
            try {
                viewHolder = viewHolderClass.newInstance();
            } catch (IllegalAccessException e) {
                Log.e(TAG, "Unable to instantiate the ViewHolder.", e);
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                Log.e(TAG, "Unable to instantiate the ViewHolder.", e);
                throw new RuntimeException(e);
            }
            viewHolder.setRootView(view);
            view.setTag(viewHolder);
        } else {
            AbstractViewHolder<TBOItem> tmpViewHolder = (AbstractViewHolder<TBOItem>) view.getTag();
            viewHolder = tmpViewHolder;
        }
        
        viewHolder.setContent(getContext().getResources(), position, item);

        return view;
    }

}
